﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using DTcms.Core.Model.Models;
using Microsoft.AspNetCore.Mvc;
using DTcms.Core.Common.Helper;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace DTcms.Core.API.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class DevController : ControllerBase
    {
        /// <summary>
        /// 生成Model类JSON字符串
        /// </summary>
        [HttpGet]
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult Index([FromQuery] string className)
        {
            var assPath = Assembly.GetEntryAssembly().Location;
            FileInfo fileInfo = new FileInfo(assPath);
            Assembly modelsAss = Assembly.LoadFile(Path.Combine(fileInfo.DirectoryName, "DTcms.Core.Model.dll"));
            IEnumerable<TypeInfo> typeInfos = modelsAss.DefinedTypes;
            TypeInfo typeInfo = typeInfos.ToList().Find(t => t.Name.ToLower() == className.ToLower());
            IEnumerable<FieldInfo> fields = typeInfo.DeclaredFields;
            if (typeInfo != null)
            {
                ConstructorInfo ci = typeInfo.GetConstructor(System.Type.EmptyTypes);
                var model = ci.Invoke(null);
                PropertyInfo[] pros = model.GetType().GetProperties();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (PropertyInfo pi in pros)
                {
                    string fieldName = pi.Name;
                    if (string.IsNullOrWhiteSpace(fieldName))
                    {
                        continue;
                    }
                    IEnumerable<Attribute> attributes = pi.GetCustomAttributes();
                    if (attributes != null)
                    {
                        List<string> validList = new List<string>();
                        string displayName = "";
                        foreach (var item in attributes)
                        {
                            string attributeName = item.GetType().Name;
                            if (attributeName == "DisplayAttribute")
                            {
                                var displayAttribute = item as DisplayAttribute;
                                displayName = displayAttribute.Name;
                            }
                            else if (attributeName == "RequiredAttribute")
                            {
                                var requiredAttribute = item as RequiredAttribute;
                                string errorMessage = string.Format(requiredAttribute.ErrorMessage, displayName);

                                validList.Add("{" + string.Format("required: true, message: '{0}', trigger: 'blur'", errorMessage) + " }");
                            }
                            else if (attributeName == "MaxLengthAttribute")
                            {
                                var maxLengthAttribute = item as MaxLengthAttribute;
                                string length = maxLengthAttribute.Length.ToString();
                                string errorMessage = string.Format(maxLengthAttribute.ErrorMessage, displayName, length);
                                validList.Add("{" + string.Format("max: {1}, message: '{0}', trigger: 'blur'", errorMessage,length) + " }");
                            }
                            else if (attributeName == "MinLengthAttribute")
                            {
                                var minLengthAttribute = item as MinLengthAttribute;
                                string length = minLengthAttribute.Length.ToString();
                                string errorMessage = string.Format(minLengthAttribute.ErrorMessage, displayName, length);
                                validList.Add("{" + string.Format("min: {1}, message: '{0}', trigger: 'blur'", errorMessage,length) + " }");
                            }

                        }
                        if (validList.Count > 0)
                        {
                            dic.Add(fieldName, validList);
                        }
                    }
                }
                string json = dic.ToJson().Replace("\"", "");

                return Ok(new { model = model.ToJson().Replace("\"",""), rules = json });
            }
            else
            {
                return Ok(new { Msg = "对象不存在!" });
            }
        }
    }
}
